package motion;

import java.awt.*;
import java.applet.*;
import java.lang.reflect.Array;

public class NewtonMotion1 extends Applet {

	public static double scale = 2;
	public Vector2D[] vectors = new Vector2D[4];
	public Vector2D total;
	
	public void init() {
		
		this.vectors[0] = new Vector2D(150, (180-11)*(Math.PI/180));
		this.vectors[1] = new Vector2D(151, 13*(Math.PI/180));
		this.vectors[2] = new Vector2D(50, ((3*Math.PI)/2));
		this.vectors[3] = new Vector2D(90, ((Math.PI)/3));
		
		this.total = new Vector2D(this.vectors);
    } 
	
	public void paint(Graphics g) {
	
		//Draw grid
		g.setColor(new Color(0xDDDDDD));
		g.drawLine(0,this.getHeight()/2,this.getWidth(),this.getHeight()/2);
		g.drawLine(this.getWidth()/2,0,this.getWidth()/2,this.getHeight());
		
		//Draw vectors
		for(int i=0; i<Array.getLength(this.vectors); i++) {
			g.setColor(Color.blue);
			int x = (int)(this.getWidth()/2)+(int)(this.vectors[i].force*scale*Math.cos(this.vectors[i].direction));
			int y = (int)(this.getHeight()/2)-(int)(this.vectors[i].force*scale*Math.sin(this.vectors[i].direction));
			this.paintArrow(g,(int)(this.getWidth()/2),(int)(this.getHeight()/2),x,y);
		}
		
		//Draw result vector
		g.setColor(Color.red);
		int x = (int)(this.getWidth()/2)+(int)(this.total.force*scale*Math.cos(this.total.direction));
		int y = (int)(this.getHeight()/2)-(int)(this.total.force*scale*Math.sin(this.total.direction));
		this.paintArrow(g,(int)(this.getWidth()/2),(int)(this.getHeight()/2),x,y);
	}
	
	private void paintArrow(Graphics g, int x0, int y0, int x1,int y1){
		int deltaX = x1 - x0;
		int deltaY = y1 - y0;
		double frac = 0.05;

		g.drawLine(x0,y0,x1,y1);
		g.drawLine(x0 + (int)((1-frac)*deltaX + frac*deltaY),
			   y0 + (int)((1-frac)*deltaY - frac*deltaX),
			   x1, y1);
		g.drawLine(x0 + (int)((1-frac)*deltaX - frac*deltaY),
			   y0 + (int)((1-frac)*deltaY + frac*deltaX),
			   x1, y1);

	    }

}
